<template>
    <div class="pkRandomBox">

        <!--随机PK 等待中-->
        <div class="pkRandomWait">

            <!--背景头像-->
            <div class="avatars">
                <div class="item" v-for="items in avatarList" >
                    <img :src='items' alt="">
                </div>
            </div>


            <!--倒计时-->
            <div class="wait">

                <div class="countdownBox">
                    <div class="circle"></div>
                    <div class="body">
                        <p>寻找小伙伴</p>
                        <div class="dotted">......</div>
                        <div class="vanCountDown">
                            <van-count-down :time="vantime" format="ss" ref="countDown" :auto-start="false" @finish="finish" class="random"/>
                        </div>
                    </div>
                </div>

            </div>

        </div>


        <!--随机PK 匹配到-->
        <div class="pkRandomMatch">

            <!--头像名称-->
            <div class="head">
                <div class="wo">
                    <div class="avatar">
                        <img :src='userinfo.headimgurl' alt="">
                    </div>
                    <span class="name">{{userinfo.nickname}}</span>
                </div>
                <div class="vs"></div>
                <div class="ta">
                    <div class="avatar">
                        <img :src='robotimg' alt="">
                    </div>
                    <span class="name" >{{robotname}}</span>
                </div>
            </div>

            <!--准备开始-->
            <div class="matchBox">
                <div class="head">
                    <p><span>PK</span>共<span>5</span>道题</p>
                    <p>得分高者获胜</p>
                </div>
                <div class="body">
                    <div class="ready"></div>
                    <div class="start"></div>
                </div>
            </div>

        </div>

    </div>
</template>
<script>

import Vue from "vue";
import {Circle, CountDown} from "vant";
import commonHelper from "../helpers/commonHelper";

Vue.use(CountDown);
Vue.use(Circle);

export default {
    name: 'pk_random',
    data() {
        return {
            uid: this.userHelper.getInfo('user_cert'),
            answerdata: {},
            userinfo: {},
            robotname: '',
            robotimg: '',
            isrobot: 0,
            gameType: '',
            roomid: '',
            userType: 0,
            vantime: 6 * 1000,  // 倒计时时间（s）
            avatarList: [],
        }

    },
    created: function () {
        this.userinfo = this.userHelper.getInfo('');
        this.userinfo.headimgurl = this.userinfo.headimgurl ? this.userinfo.headimgurl : appConfig.staticUrl + 'answerpk/img/avatar.jpg';

        this.wxShare();
    },

    mounted: function () {
        // // 开始倒计时
        // this.start();
        //
        // // 开始匹配
        // this.onopen();
        //
        // // 获取头像
        // this.getAvatars();
    },
    activated: function () {
        this.answerdata = {};
        this.robotname = '';
        this.robotimg = '';
        this.isrobot = 0;
        this.gameType = '';
        this.roomid = '';
        this.userType = 0;
        this.vantime = 6 * 1000;  // 倒计时时间（s）
        this.avatarList = [];

        // 开始倒计时
        this.start();

        // 开始匹配
        this.onopen();

        // 获取头像
        this.getAvatars();
    },
    methods: {
        // 获取头像
        getAvatars: function () {
            const _this = this;
            _this.appFetch({
                url: 'getAvatars',
                method: 'get',
            }, (res) => {
                for (let i = 0; i < 5; i++) {
                    if (res.result.data[i]) {
                        (_this.avatarList).push(res.result.data[i]);
                    } else {
                        (_this.avatarList).push(appConfig.staticUrl + "answerpk/img/avatar.jpg");
                    }
                }
            }, (error) => {
                console.log(error);
            });
        },

        // 倒计时开始
        start() {
            $(".pkRandomWait").show();
            $(".pkRandomMatch").hide();
            this.$nextTick(function () {
                this.$refs.countDown.start();
            });
        },
        pause() {
            this.$nextTick(function () {
                this.$refs.countDown.pause();
            });
        },
        reset() {
            this.$refs.countDown.reset();
        },
        finish() {
            this.quitRoom();
        },

        onopen: function () {
            this.socket.sendMessage({
                'gameType': 'pk_std',
                'type': 'match',
                'number': '2',
                'uid': this.uid,
                'nickname': this.userinfo.nickname,
                'image': this.userinfo.headimgurl,
            });
        },

        onmessage: function (e) {
            const _this = this;
            const rs = JSON.parse(e.data);
            if (rs.code == 0 && rs.type == 'matchSuccess') {
                console.log('匹配真人成功');
                //_this.stopCountDown();
                //匹配真人成功
                //clearInterval(that.data.timer);清除时间
                _this.roomid = rs.data.roomId;
                _this.userType = rs.data.userType;
                console.log(_this.roomid, rs.data);
                //var opponent = {};
                //var userInfo = //that.data.userInfo;获取用户信息
                var datas = rs.data;

                _this.isrobot = 0;

                for (var i in rs.data.userData) {
                    if (_this.uid != rs.data.userData[i].uid) {
                        _this.robotname = rs.data.userData[i].nickname;
                        _this.robotimg = rs.data.userData[i].headurl;
                        datas.robotHeader = rs.data.userData[i].headurl;
                        datas.robotName = rs.data.userData[i].nickname;
                        datas.robotuserType = rs.data.userData[i].userType;
                        localStorage.setItem('pk_user_id', rs.data.userData[i].uid);
                    } else {
                        datas.myuserType = rs.data.userData[i].userType ? rs.data.userData[i].userType : 0;
                    }
                }
                datas.gameType = 'pk_std';
                datas.isrobot = 0;
                localStorage.setItem('pkuserinfo', JSON.stringify(datas));
                localStorage.setItem('roomID', '');
                _this.goRoomWithPerson();
            }
            if (rs.code == 0 && rs.type == 'quitMatchSuccess') {
                //退出匹配
                _this.goRoomWithSingle();
            }
            if (rs.code == 2 && rs.type == 'joinRoomComplete') {
                _this.robotname = rs.data.robotName;
                _this.robotimg = rs.data.robotHeader;
                _this.isrobot = 1;

                var datas = rs.data;
                datas.isrobot = 1;
                datas.userType = 0;
                datas.gameType = 'single_std';
                datas.roomId = _this.roomid;
                var arr = [];
                var arrlength = 0;//答对个数
                var maxnum = 0;
                var minnum = 0;
                _this.answerdata.num = 5;
                switch (datas.robotright) {
                    case '1':
                        minnum = Math.round(parseInt(_this.answerdata.num) * 0.8);
                        maxnum = Math.round(parseInt(_this.answerdata.num) * 1);
                        break;
                    case '2':
                        minnum = Math.round(parseInt(_this.answerdata.num) * 0.6);
                        maxnum = Math.round(parseInt(_this.answerdata.num) * 0.8);
                        break;
                    case '3':
                        minnum = Math.round(parseInt(_this.answerdata.num) * 0.4);
                        maxnum = Math.round(parseInt(_this.answerdata.num) * 0.6);
                        break;
                }
                arrlength = _this.getRandomInt(minnum, maxnum);

                for (var i = 0; i < parseInt(_this.answerdata.num); i++) {
                    arr.push(i);
                }
                console.log(datas.robotright, '个数', arr, arrlength);
                var resultarr = _this.getArrayItems(arr, arrlength);

                datas.reultarr = resultarr;

                localStorage.setItem('pkuserinfo', JSON.stringify(datas));
                localStorage.setItem('roomID', '');

                _this.startAnswer();

            }

            if (rs.code == 3 && rs.type == 'joinRoomByPK') {
                this.startAnswer();
            }
            if (rs.code == 4 && rs.type == 'joinRoomAgain') {
                this.againAnswer('invite');
            }
        },
        /**
         * 获取一定范围随机取数
         * @return {[type]} [description]
         */
        getRandomInt: function (min, max) {
            min = Math.ceil(min);
            max = Math.floor(max);
            return Math.floor(Math.random() * (max - min + 1)) + min; //不含最大值，含最小值
        },
        /**
         * 随机取数
         * @return {[type]} [description]
         */
        getArrayItems: function (arr, num) {
            //新建一个数组,将传入的数组复制过来,用于运算,而不要直接操作传入的数组;
            var temp_array = new Array();
            for (var index in arr) {
                temp_array.push(arr[index]);
            }
            //取出的数值项,保存在此数组
            var return_array = new Array();
            for (var i = 0; i < num; i++) {
                //判断如果数组还有可以取出的元素,以防下标越界
                if (temp_array.length > 0) {
                    //在数组中产生一个随机索引
                    var arrIndex = Math.floor(Math.random() * temp_array.length);
                    //将此随机索引的对应的数组元素值复制出来
                    return_array[i] = temp_array[arrIndex];
                    //然后删掉此索引的数组元素,这时候temp_array变为新的数组
                    temp_array.splice(arrIndex, 1);
                } else {
                    //数组中数据项取完后,退出循环,比如数组本来只有10项,但要求取出20项.
                    break;
                }
            }
            return return_array;
        },

        // 去答题
        startAnswer: function () {
            const _this = this;

            // 显示匹配成功
            $(".pkRandomWait").fadeOut();
            $(".pkRandomMatch").fadeIn(function () {
                const matchBox = $(this).find(".matchBox");
                matchBox.addClass("active");
                _this.reset();
                setTimeout(function () {
                    matchBox.removeClass("active");
                    _this.$emit('handle', {name: 'pk'})
                }, 3000);
            });
        },

        // 退出房间
        quitRoom: function () {
            this.socket.sendMessage({
                'gameType': 'pk_std',
                'type': 'quitMatch',
                'uid': this.uid,
                'roomId': this.roomid,
            });
        },

        // 机器人 PK
        goRoomWithSingle: function () {
            var _this = this;
            const roomID = commonHelper.generateRoomID();
            localStorage.setItem('roomID', roomID);
            _this.roomid = roomID;
            _this.gameType = 'single_std';
            this.socket.sendMessage({
                'gameType': _this.gameType,
                'type': 'joinRoom',
                'uid': _this.uid,
                'roomId': roomID,
                'userType': '0',
            });
        },

        // 真人 PK
        goRoomWithPerson: function () {
            this.socket.sendMessage({
                'gameType': 'pk_std',
                'type': 'joinRoom',
                'roomId': this.roomid,
                'userType': this.userType,
                'uid': this.uid,
                'nickname': this.userinfo.nickname,
                'image': this.userinfo.headimgurl,
            });
        },

        // 微信分享
        wxShare: function () {
            this.wxHelper.init({
                types: ['share'],
                callback: (status) => {
                    if (status) {
                        this.wxHelper.shareMessage({
                            title: '我正在参加“党史天天学”知识竞答双人对战，快来挑战我吧！', // 分享标题
                            desc: '', // '我正在参加“党史天天学”知识竞答双人对战，快来挑战我吧！', // 分享描述
                            link: appConfig.onLineApiDomain + '/index', // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                            imgUrl: appConfig.onLineDomain + '/h5/img/wxShare.jpg', // 分享图标
                        });
                    }
                }
            });
        },
    },
}

</script>
<style lang="scss">
.vanCountDown {
    position: relative;

    .van-count-down {

        &.random{
            color:#ff5a00;
            font-size:30px;
        }
    }
}
</style>
